package grape.wx.service.mp.impl.handler;

import grape.wx.service.mp.api.handler.IMpDefaultEnhanceHander;
import grape.wx.service.mp.api.handler.IMpDefaultHandler;
import grape.wx.service.mp.reply.api.IMpMsgReplyParser;
import grape.wx.service.mp.reply.api.IMpMsgReplyService;
import grape.wx.service.mp.reply.po.MpMsgReply;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * Created by yangwei
 * Created at 2020/7/21 18:57
 */
@Slf4j
@Service
public class IMpDefaultHandlerImpl implements IMpDefaultHandler {

    @Autowired(required = false)
    private List<IMpDefaultEnhanceHander> iMpDefaultEnhanceHanderList;
    @Autowired
    private IMpMsgReplyService iMpMsgReplyService;


    @Autowired(required = false)
    private List<IMpMsgReplyParser> iMpMsgReplyParsers;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage, Map<String, Object> context, WxMpService wxMpService, WxSessionManager sessionManager) throws WxErrorException {

        // 优先执行增强处理器
        if (iMpDefaultEnhanceHanderList != null) {
            for (IMpDefaultEnhanceHander iMpDefaultEnhanceHander : iMpDefaultEnhanceHanderList) {
                if (iMpDefaultEnhanceHander.support(wxMessage,context,wxMpService,sessionManager)) {
                    return iMpDefaultEnhanceHander.handle(wxMessage,context,wxMpService,sessionManager);
                }
            }
        }
        // 自定义规则处理
        if (iMpMsgReplyParsers != null) {
            MpMsgReply matched = iMpMsgReplyService.getMatched(wxMessage, context, wxMpService, sessionManager);
            if (matched != null) {
                for (IMpMsgReplyParser iMpMsgReplyParser : iMpMsgReplyParsers) {
                    if (iMpMsgReplyParser.support(matched)) {
                        return iMpMsgReplyParser.parse(matched, wxMessage, context, wxMpService, sessionManager);
                    }
                }
            }
        }


        return null;
    }
}
